﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Common;
using log4net;
using AutoFacUtils;
using CashFlow.Web.Def;
using CashFlow.Db.DAL;
using CashFlow.Db.Entity;
using CashFlow.Db.Repository;
using CashFlow.Web.Service;

namespace CashFlow.Web.Service.Implement
{
    public class UserAccountInfoService : MyService<UserAccountInfoEntity>, IUserAccountInfoService
    {
        private IUserService GetUserService() { return AutoFacHelper.Get<IUserService>(); }

        public bool UpdateAddress(string address)
        {
            var service = GetUserService();
            var ui = service.GetLoginUser();
            using (var db = SqlSugarHelper.GetDb())
            {
                var entity = db.Queryable<UserAccountInfoEntity>().Where(x => x.UserId == ui.Id).First();
                if (entity != null)
                {
                    entity.Address = address;
                    int count = db.Updateable(entity).ExecuteCommand();
                    return count > 0;
                }
                else
                {
                    var entity2 = new UserAccountInfoEntity
                    {
                        UserId = ui.Id,
                        Address = address
                    };
                    int count = db.Insertable(entity2).ExecuteCommand();
                    return count > 0;
                }
            }
        }

        public bool UpdateAccountInfo(string bankAccountName, string bankName, string banCardNo,
            string wechatPath, string alipayPath)
        {
            var service = GetUserService();
            var ui = service.GetLoginUser();

            using (var db = SqlSugarHelper.GetDb())
            {
                var entity = db.Queryable<UserAccountInfoEntity>().Where(x => x.UserId == ui.Id).First();
                if (entity == null)
                {
                    var entity2 = new UserAccountInfoEntity
                    {
                        BankAccountName = bankAccountName,
                        Bank = bankName,
                        BankCardNo = banCardNo,
                        WechatCodePath = wechatPath,
                        AlipayCodePath = alipayPath,
                        UserId = ui.Id
                    };

                    int count = db.Insertable(entity2).ExecuteCommand();
                    return count > 0;
                }
                else
                {
                    entity.BankAccountName = bankAccountName;
                    entity.Bank = bankName;
                    entity.BankCardNo = banCardNo;
                    entity.WechatCodePath = wechatPath;
                    entity.AlipayCodePath = alipayPath;

                    int count = db.Updateable(entity).ExecuteCommand();
                    return count > 0;
                }
            }
        }
    }
}
